package com.echo.code.thread.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author baiyp
 */
public class TrialLock {

    public synchronized void lock() {
        String name = getName();
        System.out.println(name + " start-------------------->");
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(name + " wait");
                this.wait();
                System.out.println(name + " notify");
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                System.out.println(name + " break");
                break;
            }
        }
    }

    public synchronized void unlock() {
        this.notifyAll();
    }


    private String getName() {
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) {
        TrialLock simpleLock = new TrialLock();
        Thread thread = new Thread(() -> {
            simpleLock.lock();
        }, "线程一");
        thread.start();
        Thread thread1 = new Thread(() -> {
            simpleLock.lock();
        }, "线程二");
        thread1.start();
        Thread thread2 = new Thread(() -> {
            simpleLock.lock();
        }, "线程三");
        thread2.start();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
        }

        new Thread(() -> {
            thread1.interrupt();
        }, "线程四").start();


        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
        }
    }
}
